/*
 * @Author: Kang
 * @Date: 2022-02-20 08:45:52
 * @Last Modified by: Kang
 * @LastEditTime: 2022-02-22 18:35:34
 */
const SMSClient = require('@alicloud/sms-sdk');
module.exports = app => {
  const config = {
    AccessKeyId: 'LTAI4FvEcNj9kjAuhzz9kwDi', // 访问密钥编号
    AccessKeySecret: '7Fnxk1lV72O3s2Sq65PidwwyCt6hbJ', // 密钥
  };
  
  // 签名模板
  const sign = { 
    REG_CODE: {
      SignName: '安合众道', // 签名
      TemplateCode: 'SMS_200187593', // 模板
    },
  };
  class VerifService extends app.Service {

    * getMsgCode(request,code) {

      const { ctx } = this;
      const accessKeyId = config.AccessKeyId;
      const secretAccessKey = config.AccessKeySecret;
      const smsClient = new SMSClient({ accessKeyId, secretAccessKey }); // 实例化SDK

      const codeRandom = ctx.helper.randomInt(); 
      const templateParam = JSON.stringify({ code: codeRandom.toString() });
      // let tel = telCode + request.tel
      this.ctx.session.telCode  = { code: codeRandom.toString() }

      console.log(this.ctx.session)
      
      const signCode = sign[code];
      const params = {
        PhoneNumbers: request.tel,
        SignName: signCode.SignName,
        TemplateCode: signCode.TemplateCode,
        TemplateParam: templateParam,
      };
      try {
        const res = yield this.sendSms(smsClient, params);
        const result = {
            data: res,
            msg: '发送成功',
        }
        return result;
      } catch (error) {
        
      }
    }

    * create(request) {
      let result = {}
      console.log('request', request,this.ctx.session)
      const { name, tel } = request
      try {
          if(this.ctx.session.telCode.code) {
            if(request.code == this.ctx.session.telCode.code) {

              yield this.ctx.model.Customer.create({
                company_name: name,
                phone: tel,
                create_time: new Date().getTime()
              });
              result = {
                status: 200,
                data: null,
                msg: '提交成功',
              }
            } else {
              result = {
                status: 500,
                data: null,
                msg: '验证码错误！',
              }
            }
          } else {
            result = {
              status: 500,
              data: null,
              msg: '验证码已过期！',
            }
          }
          
          return result;
      } catch (error) {
        console.log(error)
        // result = {
        //   status: 500,
        //   data: null,
        //   msg: '提交失败，请稍后重试！',
        // }
        // return result;
      }
    }

    async sendSms(smsClient, params) {
      return new Promise((resolve, reject) => {
        smsClient.sendSMS(params).then(result => {
          resolve(result);
        }, ex => {
          reject(ex);
        });
      });
    }
  }
  return VerifService;
}
  


